import Vue from 'vue'
import config from '../config.js'
import store from '@/store'
import utils from './utils.js'
import Request from "./http.js";
//分享
let baseBath, shareImage;
let mallShare = {}; //mall商城分享信息；
//#ifdef H5
const jweixin = require('jweixin-module')
baseBath = location.origin + config.basePath; //"/mgmall_test/"
shareImage = "http://ss.migudm.cn/mgmall/shareImgSmallEOc.png"
//#endif
const $request = Request.mgHttp
// var wxAppId = 'gh_2c84da305251' 圈圈小程序原始ID
const wxAppId = 'gh_29a14341ee5c' //新商城小程序原始ID
const self = Vue.prototype

export default class Share {
	constructor() {
	   this.baseBath = baseBath
	}
	copyShare(shareInfo) {
		let entrance = store.state.entrance;
		let isSDK = store.state.isSDK;//直播带货SDK在视讯中无法分享 bug47832
		shareInfo.linkUrl = this.addChannelID(shareInfo.linkUrl);
		if (entrance == "app" && !isSDK) {
			this.bridgeShare(shareInfo, 'pullShare')
		} else if (entrance == "mp-weixin") {

		} else { //h5
			self.$copyText(baseBath + shareInfo.linkUrl).then((e) => {
				utils.toast("已复制链接至剪切板，快去分享链接吧～")
			}, (e) => {
				console.log(e)
			})
		}
	}

	//添加ccid shortId
	addChannelID(url) {
		let entrance = store.state.entrance;
		let sc = store.state.scene.sc;
		let mgdbId = store.state.scene.mgdbId || '';
		let shortId = store.state.buryPoint.shortId || '';
		if (url.indexOf('sc=') == -1 && sc) {
			url += `${url.indexOf('?') == -1 ? '?' : '&'}sc=${sc}`
		}
		if (url.indexOf('shortId=') == -1 && shortId) {
			url += `${url.indexOf('?') == -1 ? '?' : '&'}shortId=${shortId}`
		}
		if (entrance == "app" && url.indexOf('fromShare=mgqqshare=') == -1) {
			if (url.indexOf('?') > -1) {
				url = url + "&fromShare=mgqqshare" + store.state.platformName
			} else {
				url = url + "?fromShare=mgqqshare" + store.state.platformName;
			}
		}
		if (url.indexOf('mgdbId=') == -1 && mgdbId) {
			url += `${url.indexOf('?') == -1 ? '?' : '&'}mgdbId=${mgdbId}`
		}
		return url;
	}

	bridgeShare(obj, type) {
		let linkUrl = baseBath + obj.linkUrl;
		if(linkUrl.indexOf('fromShare=mgqqshare=') == -1){
			if (linkUrl.indexOf('?') > -1) {
				linkUrl = linkUrl + "&fromShare=mgqqshare" + store.state.platformName
			} else {
				linkUrl = linkUrl + "?fromShare=mgqqshare" + store.state.platformName
			}
		}
		bridge.on("share", function(data, response) {
			// alert('bridge'+JSON.stringify(obj))
			response.success({
				title: obj.title, //string 分享标题
				desc: obj.desc, //string 分享描述
				link: linkUrl, //string 分享链接
				imgUrl: obj.imageUrl, //string 分享图标
				targetId: obj.targetId, //string 分享目标ID（取数用）
				targetType: obj.targetType, //string 分享目标类型（取数用）
				// wxThumb: obj.imageUrl,
				// wxAppId: wxAppId,
				// wxPath: obj.linkUrl, //先除了详情页其他页面分享都是首页
			});
		})
		if (type == "pullShare") {
			bridge.fire('showShareView')
		}
	}

	// 收藏分享
	collectShare(obj) {
		let entrance = store.state.entrance;
		try{
			obj.linkUrl = this.addChannelID(obj.linkUrl);
		}catch(e){
			//TODO handle the exception
		}
		if (entrance == "app") {
			this.bridgeShare(obj, 'pullShare')
		} else { //h5
			utils.toast("已复制链接至剪切板，快去分享链接吧～")
		}
	}

	//详情页分享
	detailShare(shareInfo) {
		mallShare = shareInfo;
		let entrance = store.state.entrance;
		try{
			shareInfo.linkUrl = this.addChannelID(shareInfo.linkUrl);
		}catch(e){
			//TODO handle the exception
		}
		if (entrance == "app") {
			this.bridgeShare(shareInfo)
		} else if (entrance == "weixin") {
			let after_url = shareInfo.linkUrl.indexOf('?') != -1 ? "&shareType=1" : "?shareType=1"
			shareInfo.linkUrl = shareInfo.linkUrl + after_url
			this.wxShare(shareInfo)
		}
	}

	//其他分享
	commonShare() {
		let entrance = store.state.entrance;
		let shareInfo = {
			title: "福建省博士创新站",
			desc: "这里有专业大神评测帮你精准种草避免踩雷！还有授权手办、软萌盲盒等你挑选~",
			linkUrl: '',
			imageUrl: shareImage,
		}
		mallShare = shareInfo;
		if (entrance == "app") {
			this.bridgeShare(shareInfo)
		} else if (entrance == "weixin") {
			this.wxShare(shareInfo)
		}
	}

  buildWxShareUrl(url, queryParam = {}) {
		const param = utils.deleteNullData(Object.assign({
			companyId: store.state.companyId,
			wxShareChannel: store.state.channel
		}, queryParam))
		return utils.appendParamsToUrl(url, param)
	}

	//小程序分享
	mpweixinShare(param, url = '/pages/user/benefits', queryParam = {}) {
		const shareUrl = this.buildWxShareUrl(url, queryParam)
		const shareParam = param || {}
		return {
			title: shareParam.title || "上咪Mall，发现潮流好物", //分享内容
			desc: shareParam.text || "这里有专业大神评测帮你精准种草避免踩雷！还有授权手办、软萌盲盒等你挑选~",
			path: shareUrl, //分享地址
			imageUrl: shareParam.largeImageUrl || 'http://ss.migudm.cn/mgmall/shareImageEoc.png', //分享图片
		}
	}

	wxShare(shareInfo) {
		let url = location.href; //域名校验
		let lastUrl = baseBath + shareInfo.linkUrl
		lastUrl = this.addChannelID(lastUrl);
		$request('common/wechat/getJSSDKConfig', {
			url: url
		}, 'api', false, null, false).then(
			data => {
				let res = data.config;
				jweixin.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: res.appId, // 必填，公众号的唯一标识
					timestamp: res.timestamp, // 必填，生成签名的时间戳
					nonceStr: res.nonceStr, // 必填，生成签名的随机串
					signature: res.signature, // 必填，签名，见附录1
					jsApiList: res.jsApiList
				});
				jweixin.onMenuShareAppMessage({
					title: shareInfo.title,
					desc: shareInfo.desc,
					// link: baseBath + shareInfo.linkUrl,
					link: lastUrl,
					imgUrl: shareInfo.imageUrl,
					// type:'link',
					trigger: function(res) {
						// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
						// alert('用户点击发送给朋友');
					},
					success: function(res) {
						//alert('已分享');
					},
					cancel: function(res) {
						//alert('已取消');
					},
					fail: function(res) {
						//alert(JSON.stringify(res));
					}
				});
				jweixin.onMenuShareTimeline({
					title: shareInfo.title,
					desc: shareInfo.desc,
					link: lastUrl,
					imgUrl: shareInfo.imageUrl,
					// type:'link',
					trigger: function(res) {
						// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
						// alert('用户点击发送给朋友');
					},
					success: function(res) {
						//alert('已分享');
					},
					cancel: function(res) {
						//alert('已取消');
					},
					fail: function(res) {
						//alert(JSON.stringify(res));
					}
				});
			},
			error => {
				return false
			}
		);
	}

	//视讯 咪咕视频客户端分享
	sxShare(shareData) {
		if (!shareData.title) { //没有传参数，取商城自带分享参数
			shareData = mallShare;
		}
		let pageUrl = location.href;
		if (pageUrl.indexOf('?') > -1) {
			pageUrl = pageUrl + "&fromShare=mgsxshare" + store.state.platformName
		} else {
			pageUrl = pageUrl + "?fromShare=mgsxshare" + store.state.platformName
		}
		var shareData = {
			name: 'SHARE_BUTTON_CLICK',
			type: 'USER_INTERACTION_SHARE',
			params: {
				path: '',
				frameID: '',
				contentID: '',
				location: 'WEB_VIEW_H5',
				pageID: '',
				url: pageUrl,
				extra: {
					shareUrl: pageUrl,
					shareTitle: shareData.title,
					shareSubTitle: shareData.desc,
					imgUrl: shareData.imageUrl,
					contentId: '',
					contentType: '',
					icon: shareData.imageUrl,
					shareType: 'NORMAL'
				}
			}
		};
		bridge.fire('CallNative', shareData);
	}

	baMinShare(shareData) {
		if (!shareData.title) { //没有传参数，取商城自带分享参数
			shareData = mallShare;
		}
		let pageUrl = location.href;
		if (pageUrl.indexOf('?') > -1) {
			pageUrl = pageUrl + "&share=baminshare" + store.state.platformName
		} else {
			pageUrl = pageUrl + "?share=baminshare" + store.state.platformName
		}
		const json = {
			"serviceName": "share",
			"shareUrl": pageUrl,
			"infoTitle": shareData.title,
			"info": shareData.desc,
			"tplIcon": "",
			"isShare": 806,
			"isCallBack": true,
			"tplId": 18705,
			"channels": [{
				"channelImg": "http://app.fmcc.com.cn:6001/FNllms/uploadRoot/share_channel/android/circle_new.png",
				"channelName": "微信朋友圈",
				"channelType": 1
			}, {
				"channelImg": "http://app.fmcc.com.cn:6001/FNllms/uploadRoot/share_channel/android/wechat_new.png",
				"channelName": "微信",
				"channelType": 2
			}, {
				"channelImg": "http://app.fmcc.com.cn:6001/FNllms/uploadRoot/share_channel/android/qq_new.png",
				"channelName": "QQ好友",
				"channelType": 9
			}]
		};
		location.href = "URL:" + JSON.stringify(json);
	}
}
